package com.iuie.ns.devtools.element;

import java.util.ArrayList;
import java.util.List;

import com.iuie.ns.frame.utils.StringUtils;

public class SQLInsertElement extends DevElement {
	
	private ResultMapOperationElement operationElement;
	
	public SQLInsertElement(ResultMapOperationElement operationElement) {
		this.operationElement = operationElement;
	}

	@Override
	protected String getPrefix() {
		StringBuilder sb = new StringBuilder(12);
		if (StringUtils.equals(this.operationElement.getOperation(), "addOne")) {
			return "\t\tinsert into " + operationElement.getHeader().getTableName() + " (\n\t\t\t";
		}
		if (StringUtils.equals(this.operationElement.getOperation(), "batchAdd")) {
			sb.append("\t\t<if test=\"records != null and records.size() > 0\">\n\t\t\t");
			sb.append("insert into " + operationElement.getHeader().getTableName() + " (\n\t\t\t\t");
			return sb.toString();
		}
		return null;
	}

	@Override
	protected String getSuffix() {
		if (StringUtils.equals(this.operationElement.getOperation(), "batchAdd")) {
			return "\t\t</if>";
		}
		return null;
	}

	@Override
	protected List<DevElement> getChildren() {
		List<DevElement> list = new ArrayList<>();
		list.add(this.operationElement.getSQLFieldElement());
		if (StringUtils.equals(this.operationElement.getOperation(), "addOne")) {
			list.add(new BaseDevElement("\n\t\t) values (\n\t\t\t"));
			list.addAll(this.operationElement.getMyBatisValueElements(3));
			list.add(new BaseDevElement("\n\t\t)"));
		}
		if (StringUtils.equals(this.operationElement.getOperation(), "batchAdd")) {
			list.add(new BaseDevElement("\n\t\t\t)\n"));
			String prefix = "\t\t\t<foreach collection=\"records\" item=\"item\" index=\"index\" separator=\"union all\" >\n";
			String suffix = "\t\t\t</foreach>\n";
			DevElement element = new BaseDevElement("\t\t\t\t(select ", this.operationElement.getMyBatisValueElements(4), " from dual)\n");
			list.add(new BaseDevElement(prefix, element, suffix));
		}
		return list;
	}

}
